<?php

class Menu extends Menu_model {

    function __construct() {
        parent::__construct();
    }
    
    public static function getMenuList(&$array_menus = array(), $filter = array()) {
        $menu = new Menu();
        if (isset ($filter['parent_id'])) {
            $menu->addWhere("id_parent = ".$filter['parent_id']);
        }
        if (isset ($filter['type'])) {
            $menu->addWhere("type = ".$filter['type']);
        }
        $menu->disabled = 0;
		$menu->orderBy('position');
        $menu->find();
        while($menu->fetchNext()) {
            $menu_array = array();
            $menu_array['ID'] = $menu->id;
            $menu_array['NAME'] = $menu->name;
            $menu_array['POSITION'] = $menu->position;
            $menu_array['LINK'] = $menu->link;
            $menu_array['SECTION'] = $menu->section;
            $menu_array['ID_PARENT'] = $menu->id_parent;
            $menu_array['ALLOW_ACCESS'] = explode(",", $menu->permission);
            
            if ($menu->id_parent == 0) {
                $array_menus[$menu->id]['parent'] = $menu_array;
            } else {
                $array_menus[$menu->id]['child'] = $menu_array;
            }
            $filter['parent_id'] = $menu->id;
            self::getMenuList($array_menus[$menu->id]['childs'], $filter);
		}
    }
    
    function getList($filter = array()) {
        $menu = new Menu();
        if(isset($filter['name']) && $filter['name']) {
            $menu->addWhere("name LIKE '%".$filter['name']."%'");
        }
        if(isset($filter['type']) && $filter['type']) {
            $menu->addWhere("type = ".$filter['type']."%'");
        }
        $menu->orderBy("name");
        $menu->find();

        return $menu;            
    }
    
    function validateInput() {

        if (!empty ($this->permission)) {
            $group_ids = $this->permission;
            foreach($group_ids as $group_id) {
                $group = new Group();
                if (!$group_id || !$group->get($group_id)) {
                    MessageHandler::add (_MSG_GROUP_NAME_NOT_EXISTS, MSG_ERROR, LOG_ONLY);
                    return false;
                }
            }
            $this->permission = ADMIN.','.implode(",", $group_ids);
        }
         
        return MessageHandler::countError() > 0 ? false : true;

    }
    
    public function isDisabled($id = 0, $value = 0) {
		$menu = new Menu();
		if (!$id || !$menu->get($id)) {
			return '0';
		}
		$menu->disabled = $value;
        $menu->update();
		
		return '1';
	}
}
